package com.jn.algorithm.day001.question4;

import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @author 江南大学1033190417
 * @date 2022/4/15 23:55
 */
public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        Queue<Integer> queue = new PriorityQueue<>();
        for (int i = 0; i < nums1.length; i++) {
            queue.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            queue.add(nums2[i]);
        }
        int count = 0;
        int size = queue.size();
        if (size % 2 == 1) {
            while (!queue.isEmpty()) {
                Integer poll = queue.poll();
                if (count == size / 2) {
                    return Double.parseDouble(poll.toString());
                }
                count++;
            }
            return 0.0;
        } else {
            Integer num1 = 0, num2 = 0;
            while (!queue.isEmpty()) {
                Integer poll = queue.poll();
                if (count == size / 2 - 1) {
                    num1 = poll;
                }
                if (count == size / 2) {
                    num2 = poll;
                    break;
                }
                count++;
            }
            System.out.println(Double.parseDouble(num1.toString()));
            System.out.println(Double.parseDouble(num2.toString()));
            return (Double.parseDouble(num1.toString()) + Double.parseDouble(num2.toString())) / 2;
        }

    }

    public double findMedianSortedArrays2(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int in = l1 + l2;
        int[] nums = new int[in];

        int i = 0, j = 0;
        while (i < l1 && j < l2) {
            if (nums1[i] <= nums2[j]) {
                nums[i + j] = nums1[i];
                i++;
            } else {
                nums[i + j] = nums2[j];
                j++;
            }
        }
        for (int k = i; k < l1; k++) {
            nums[i + j + k - i] = nums1[k];
        }
        for (int k = j; k < l2; k++) {
            nums[i + j + k - j] = nums2[k];
        }
        if (in % 2 == 1) {
            return nums[in / 2];
        } else {
            return ((double) nums[in / 2 - 1] + nums[in / 2]) / 2;
        }
    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = new int[]{1, 2};
        int[] nums2 = new int[]{3, 4};
        System.out.println(solution.findMedianSortedArrays2(nums1, nums2));

    }
}
